from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
import time
service = ChromeService(executable_path='chromedriver.exe')
url = 'http://www.baidu.com'
browser = webdriver.Chrome(service=service)

def opera_browser(browser):
    browser.get(url)
    # 设置不自动关闭游览器
    options = webdriver.ChromeOptions()
    options.add_experimental_option('detach', True)  # 不自动关闭浏览器
    time.sleep(2)
    # 获取文本框
    input = browser.find_element(by=By.ID, value='kw')
    # 文本框输入周杰伦
    input.send_keys('周杰伦')
    # 获取点击框
    button = browser.find_element(by=By.ID, value='su')
    button.click()
    time.sleep(2)
    # 滑到底部 window.scrollTo(0, document.body.scrollHeight);
    # js_bottom = "window.scrollTo(0, document.body.scrollHeight);"  # documentElement表示获取根节点元素
    # js_bottom = "window.scrollTo(0,document.body.scrollHeight);"
    js_bottom = 'document.documentElement.scrollTop=10000'
    browser.execute_script(js_bottom)
    time.sleep(2)
    # 获取下一页按钮
    next = browser.find_element(by=By.CLASS_NAME,value='n')
    # 点击下一页
    next.click()
    time.sleep(2)
    # 返回上一页
    browser.back()
    time.sleep(2)
    # 回到首页
    browser.forward()
    time.sleep(2)
    browser.quit()
opera_browser(browser)
